package drone.basis.util;

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSONObject ;

public class AesUtil {

	private static final String AESTYPE = "AES/ECB/PKCS5Padding";
	public static final String KEY = "99012345678901234567890123456789";

	public static String AES_Encrypt(String keyStr, String plainText) throws Exception {
		byte[] encrypt = null;
		Key key = generateKey(keyStr);
		Cipher cipher = Cipher.getInstance(AESTYPE);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		encrypt = cipher.doFinal(plainText.getBytes());
		return Base64.getEncoder().encodeToString(encrypt);
	}
	
	public static String AES_Decrypt(String keyStr, String encryptData) throws Exception {
		byte[] decrypt = null;
		Key key = generateKey(keyStr);
		Cipher cipher = Cipher.getInstance(AESTYPE);
		cipher.init(Cipher.DECRYPT_MODE, key);
		decrypt = cipher.doFinal(Base64.getDecoder().decode(encryptData));
		return new String(decrypt).trim();
	}

	private static Key generateKey(String key) throws Exception {
		SecretKeySpec keySpec = new SecretKeySpec(HexString2Bytes(key), "AES");
		return keySpec;
	}

	private static byte uniteBytes(byte src0, byte src1) {
		byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
		_b0 = (byte) (_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
		byte ret = (byte) (_b0 | _b1);
		return ret;
	}

	public static byte[] HexString2Bytes(String src) {
		byte[] ret = new byte[src.length() / 2];
		byte[] tmp = src.getBytes();
		for (int i = 0; i < src.length() / 2; ++i) {
			ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
		}
		return ret;
	}

	public static void main(String[] args) throws Exception {
		try {
			// String s="dr+XCNcyAOOMVSw+6xJ4GznoAHJrAIOADTnQTcdCEDc=";
			
			JSONObject paramObject = new JSONObject ( ) ;
			paramObject.put ( "startDate" , "2023-05-28" ) ;
			paramObject.put ( "endDate" , "2023-05-29" ) ;
			paramObject.put ( "pageNumber" , "1" ) ;
			
			System.out.println ( paramObject.toJSONString ( ) ) ;
			
			System.out.println(AES_Encrypt("7aa86737fece42918fdd9d8d343cfef6", paramObject.toJSONString ( )));
			 System.out.println( AES_Decrypt("7aa86737fece42918fdd9d8d343cfef6", "1EByC9gYldehYYnPH9921EYSMY1xjRkEQhglqUlJjGtXAOat5sMTidN1LVVDScMF3wg5re7CvPmNc9pZZcwqAwODhfFdG1t2X9+tDlCTxIU="));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}